package com.shhm.config;

import com.github.benmanes.caffeine.cache.Cache;
import com.shhm.common.entity.admin.SysRoleOperatePerms;
import com.shhm.common.entity.system.SysPassAuth;
import com.shhm.common.mapper.SysRoleOperatePermsMapper;
import com.shhm.exception.JwtAccessDeniedHandler;
import com.shhm.exception.JwtAuthenticationEntryPoint;
import com.shhm.filter.JwtAuthenticationFilter;
import com.shhm.filter.JwtAuthorizationFilter;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.util.List;

/**
 * @author JackZ
 * @version 1.0
 * @description: 用户认证和授权登录配置(security)
 * @date 2025/7/12 下午5:06
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Resource
    private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
    @Resource
    private JwtAccessDeniedHandler jwtAccessDeniedHandler;
    @Resource
    private RedisTemplate<String, String> redisTemplate;
    @Resource
    private SysRoleOperatePermsMapper roleOperatePermsMapper;
    @Resource(name = "PermissionsCache")
    private Cache<String, List<SysRoleOperatePerms>> localPermissionsCache;
    @Resource(name = "WhiteListCache")
    private Cache<String, List<SysPassAuth>> localSysPassAuthCache;

//    令牌认证过滤URI
    private final String[] PASS_AUTHENTICATION_URI={"/public/","/test/"};
    // 令牌鉴权过滤URI
    private final String[] PASS_AUTHORIZATION_URI={"/public/","/test/","/system/user/router/","/home/","/business/"};

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        return http.
                authorizeHttpRequests(ahr->ahr.anyRequest().permitAll()).
                csrf(csrf->csrf.disable())
                .sessionManagement(smm->smm.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .addFilterBefore(new JwtAuthenticationFilter(PASS_AUTHENTICATION_URI,redisTemplate,localSysPassAuthCache,passwordEncoder()), UsernamePasswordAuthenticationFilter.class)
                .addFilterAfter(new JwtAuthorizationFilter(redisTemplate,PASS_AUTHORIZATION_URI,roleOperatePermsMapper,localPermissionsCache,localSysPassAuthCache), JwtAuthenticationFilter.class)
                .build();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

}
